<template>
  <div class="profile-container">
    <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        size="default"
        label-width="100px"
        style="max-width: 500px;"
    >
      <el-form-item label="头像" prop="image">
        <div class="avatar-container">
          <img :src="imageUrl" alt="Uploaded Image will appear here" id="uploadedImage" class="avatar-image">
          <br>
          <el-button @click="triggerFileInput">修改头像</el-button>
          <input type="file" ref="imageInput" accept="image/*" @change="updateAvatar" style="display: none;">
        </div>
      </el-form-item>
      <el-form-item label="昵称" prop="userName">
        <rl-row>
          <el-input v-model="formData.userName" placeholder="请输入昵称"></el-input>
          <el-button type="primary" @click="submitUserName">修改</el-button>
        </rl-row>
      </el-form-item>
      <el-form-item label="密码">
        <a href="javascript:void(0)" class="a-link" @click="showUpdatePassword">修改密码</a>
      </el-form-item>
      <el-form-item label="兴趣" prop="hobbies">
        <div class="hobbiesGroup">
          <el-row>
            <el-button type="primary" @click="showEdit">新增兴趣</el-button>
          </el-row>
          <div class="hobbies-container">
            <el-tag v-for="hobby in hobbies" :key="hobby.id" closable @close="delHobby(hobby)" type="primary">
              {{ hobby.tagName }}
            </el-tag>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <AdminDialog
        :show="dialogConfig.show"
        :title="dialogConfig.title"
        :buttons="dialogConfig.buttons"
        width="400px"
        @close="dialogConfig.show = false"
    >
      <el-form :model="passwordFormData" :rules="rules" ref="passwordFormRef" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input placeholder="请输入原密码" type="password" v-model="passwordFormData.oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入密码" type="password" v-model="passwordFormData.password"></el-input>
        </el-form-item>
        <el-form-item label="重复密码" prop="rePassword">
          <el-input placeholder="请再次输入密码" type="password" v-model="passwordFormData.rePassword"></el-input>
        </el-form-item>
      </el-form>
    </AdminDialog>
    <AdminDialog
        :show="hobbiesDialogConfig.show"
        :title="hobbiesDialogConfig.title"
        :buttons="hobbiesDialogConfig.buttons"
        width="500px"
        @close="hobbiesDialogConfig.show = false"
    >
      <Table
          :columns="columns"
          :showPagination="false"
          :dataSource="hobbiesData"
          :fetch="loadHobbiesList"
          :options="{ selectType: 'checkbox', extHeight: 20 }"
          @rowSelected="handleRowSelected"
      ></Table>
    </AdminDialog>
  </div>
</template>

<script>
import { getCurrentInstance, nextTick } from 'vue';
import store from '../../store';
export default {
  data() {
    return {
      proxy: getCurrentInstance().proxy,
      formDataRef: null,
      passwordFormData: {},
      passwordFormRef: null,
      selectedHobbiesId: [],
      rules: {
        nickName: [{ required: true, message: '昵称不能为空' }],
        oldPassword: [{ required: true, message: '请输入原密码' }],
        password: [
          { required: true, message: '请输入密码' },
          {
            validator: this.Verify.password,
            message: '密码最少8位，只能输入数字或字母',
          },
        ],
        rePassword: [
          { required: true, message: '请再次输入密码' },
          {
            validator: this.validateRePass,
            message: '两次输入的密码不一致',
          },
        ],
      },
      hobbies: [],
      columns: [
        {
          label: '标签名称',
          prop: 'tagName',
        },
      ],
      hobbiesData: {
        list: [],
      },
      formData: {},
      dialogConfig: {
        show: false,
        title: '修改密码',
        buttons: [
          {
            type: 'danger',
            text: '确定',
            click: (e) => {
              this.submitPassword();
            },
          },
        ],
      },
      hobbiesDialogConfig: {
        show: false,
        title: '新增兴趣',
        buttons: [
          {
            type: 'danger',
            text: '确定',
            click: (e) => {
              this.submitHobbies();
            },
          },
        ],
      },
      imageUrl: 'https://blog240702.oss-cn-hangzhou.aliyuncs.com/35fd3225-a510-4dd2-9506-11dc0b4138f5.png',
    };
  },
  methods: {
    showUpdatePassword() {
      this.dialogConfig.show = true;
      this.$nextTick(() => {
        console.log(this.passwordFormRef);
        this.$refs.passwordFormRef.resetFields();
        this.$refs.passwordFormData = {};
      });
    },
    validateRePass(rule, value, callback) {
      if (value !== this.passwordFormData.password) {
        callback(new Error(rule.message));
      } else {
        callback();
      }
    },
    //修改昵称
    async submitUserName(){
      try{
        let result =await this.proxy.Request({
          url:"/currentUser/update",
          method:'PUT',
          params:{
            username:this.formData.userName,
          },
        });
        if(!result){
          return;
        }
        this.proxy.Message.success("昵称修改成功");
        const currentUserInfo = this.$store.getters.loginUserInfo;
        const updateUserInfo = {
          ...currentUserInfo,
          username: this.formData.userName,
        };
        this.$store.commit('updataLoginUserInfo',updateUserInfo);
        console.log(localStorage)
      }catch(error){
        console.error("修改用户昵称时出现问题",error)
      }
    },
    submitPassword() {
      console.log(this.passwordFormData);
      this.$refs.passwordFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        let params = {
          oldPassword: this.passwordFormData.oldPassword,
          newPassword: this.passwordFormData.password,
        };
        let result = await this.proxy.Request({
          url: '/currentUser/password',
          method: 'PUT',
          params,
        });
        if (!result) {
          return;
        }
        this.dialogConfig.show = false;
        this.proxy.Message.success('修改成功');
      });
    },
    async loadHabbies() {
      try {
        let result = await this.proxy.Request({
          url: '/hobbies/currentUser',
          method: 'GET',
        });
        if (!result) {
          return;
        }
        this.hobbies = result.data;
      } catch (error) {
        console.error('获取标签数据时出错：', error);
      }
    },
    showEdit() {
      this.loadHabbiesList();
      this.hobbiesDialogConfig.show = true;
    },
    async loadHabbiesList() {
      try {
        let result = await this.proxy.Request({
          url: '/tags',
          method: 'GET',
        });

        if (!result) {
          return;
        }
        this.hobbiesData.list = result.data;
      } catch (error) {
        console.error('获取标签数据时出错：', error);
      }
    },
    handleRowSelected(selectedIds) {
      this.selectedHobbiesId = selectedIds;
      console.log(this.selectedHobbiesId);
    },
    async submitHobbies() {
      if (!!this.selectedHobbiesId) {
        console.log(this.selectedHobbiesId);
        console.log(localStorage);
        const data = {
          tagIds: [...this.selectedHobbiesId],
        };
        try {
          let result = await this.proxy.Request({
            url: '/hobbies',
            method: 'POST',
            data,
            headers: {
              'Content-Type': 'multipart/form-data',
            },
          });
          this.hobbiesDialogConfig.show = false;
          this.loadHabbies();
          console.log(result);
          if (!result) {
            return;
          }
        } catch (error) {
          console.error(error);
        }
      }
    },
    delHobby(data) {
      this.proxy.Confirm('你确定要删除该兴趣吗?', async () => {
        let result = await this.proxy.Request({
          url: 'hobbies/delete/' + data.id,
          method: 'DELETE',
        });
        if (!result) {
          return;
        }
        this.loadHabbies();
      });
    },
    triggerFileInput() {
      this.$refs.imageInput.click();
    },
    async updateAvatar() {
      const imageInput = this.$refs.imageInput;

      if (imageInput.files.length === 0) {
        alert('Please select an image!');
        return;
      }

      const formData = new FormData();
      formData.append('image', imageInput.files[0]);

      try {
        let response = await this.proxy.Request({
          url:`/currentUser/update`,
          method: 'PUT',
          data:formData,
          headers:{
            'Content-Type': 'multipart/form-data',
          }
        })
        console.log(response)

        console.log("test")
        console.log("data is",response.data)

        if (response.code === '1') {
          let result =await this.proxy.Request({
            url:'/currentUser/info',
            method:'GET',
          })
          this.$store.commit("updataLoginUserInfo", result.data);
          var userInfo = eval("("+localStorage.userInfo+")");
          this.imageUrl = userInfo.loginUserInfo.image;
          console.log("new local is",localStorage)
        } else {
          throw new Error(response.msg || 'Unknown error');
        }
      } catch (error) {
        console.error('An error occurred while updating avatar:', error);
      }
    },
    loadUserInfo() {
      var userInfo = eval('(' + localStorage.userInfo + ')');
      console.log(userInfo);
      this.formData.userName = userInfo.loginUserInfo.username;
      this.imageUrl = userInfo.loginUserInfo.image || this.imageUrl;
    },
  },
  mounted() {
    this.loadHabbies();
    this.loadUserInfo();
    console.log(localStorage)
  },
};
</script>

<style scoped>
.avatar-image {
  width: 100px; /* 设置宽度，可以根据需要调整 */
  height: 100px; /* 设置高度，可以根据需要调整 */
  border-radius: 50%; /* 将图片设置为圆形 */
  object-fit: cover; /* 保持图片的宽高比，并且覆盖整个容器 */
  display: block; /* 确保图片显示为块级元素 */
  margin: 0 auto; /* 使图片水平居中 */
}
.profile-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  border-radius: 10px;
}
.hobbies-container {
  height: 120px;
  width: 400px;
  margin-top: 10px;
  border-radius: 5px;
  background-color: aliceblue;
}
.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avatar-image {
  margin-top: 20px;
  max-width: 100%;
}
</style>
